const express = require('express');

const routes = express.Router();

//引入mysql
const mysql = require('mysql');
//创建连接池
var pool = mysql.createPool({
    connectionLimit : 10,
    host : 'localhost',
    user : 'root',
    password : 'root',
    database : 'stumsg'
})


routes.route('/')
    .get( (req,resp)=>{

        //获取cookies
        var uid = req.cookies.uid;
        var gender = req.cookies.gender;
        //获取当前教师的专业id
        var sub_id = req.cookies.sub_id;
        //学号
        var stu_uid = req.query.uid;
        //console.log(stu_uid)
        //判断
        if(gender == 1){
            var pname = '教师';
        }else {
            var pname = '学生';

        }

        //查询要删除的学生姓名
        var sql = `SELECT stu_name , uid  FROM stu_list WHERE uid = ${stu_uid}`;

        pool.getConnection( (err , connection)=>{
            if(err) throw err;

            connection.query( sql , (error , result)=>{

                //执行成功  释放连接
                connection.release();

                resp.render('stu_delete',{
                    uid : uid,
                    pname : pname,
                    sub_id : sub_id,
                    result : result,
                })
                //console.log(result)
                if(error) throw error;
            } )
        } )
    })

.post( (req,resp)=>{
    //学号
    var stu_uid = req.body.uid;
    //删除
    var sql = `DELETE FROM stu_list WHERE stu_list.uid = ${stu_uid}`;
    //console.log(sql)
    pool.getConnection( (err , connection)=>{
        if(err) throw err;

        connection.query( sql , (error , result)=>{


            //console.log(sql_scores)
            //第一条sqlyuju执行成功才会执行第二条sql
            if(result){
                var sql_scores = `DELETE FROM scores WHERE scores.uid = ${stu_uid}`;
                connection.query( sql_scores , (errs , res)=>{
                    //执行成功  释放连接
                    connection.release();
                    if(res){
                        resp.redirect('/sel_list')
                    }
                    //console.log(result)
                    if(errs) throw errs;
                } )
            }
            //console.log(result)
            if(error) throw error;
        } )
    } )

} )

//暴露接口
module.exports = routes;